package com.chy.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chy.mapper.CatalogMapper;
import com.chy.pojo.Catalog;

@Service
/**
 * 
 * @author admin
 * @date 2019年8月20日
   *    业务层,主要负责处理前后端不一致的业务
 */
public class CatalogServiceImpl implements CatalogService{
    //记录日志(阿里规约建议使用slf4j)
    private static final Logger LOGGER = LoggerFactory.getLogger(CatalogServiceImpl.class);
    
    @Autowired
    private CatalogMapper catalogMapper;
    
    //查询子结点
    @Override
    public List<Catalog> getByPid(long pid) {
        // TODO Auto-generated method stub
        try {
            return catalogMapper.selectByPid(pid);
        } catch (Exception e) {
            // 记录日志
            LOGGER.error("get catalog children by pid="+pid);
            throw e;
        }
    }
    
    //添加方法
    @Override
    public int add(Catalog catalog) {
        // TODO Auto-generated method stub
        Catalog catalog2 = catalogMapper.selectByPrimaryKey(catalog.getPid());
        if(!catalog2.getIsParent()) {
            catalog2.setIsParent(true);
            catalogMapper.updateByPrimaryKeySelective(catalog2);
        }
        return catalogMapper.insert(catalog);
    }
    
    //修改
    @Override
    public int update(Catalog catalog) {
        // TODO Auto-generated method stub
        return catalogMapper.updateByPrimaryKeySelective(catalog);
    }
    
    //删除数据
    //使用递归方法从下面的结点依次向上删除
    //并在删除完成之后判断父级是否还有子节点
    //如果父级没有子节点则将父级的属性置为非父结点
    @Override
    public void delete(Catalog catalog) {
        // TODO Auto-generated method stub
        Catalog cata = catalogMapper.selectByPrimaryKey(catalog.getId());
        if(!cata.getIsParent()) {
            catalogMapper.deleteByPrimaryKey(cata.getId());
        }else {
            List<Catalog> list = catalogMapper.selectByPid(catalog.getId());
            for (Catalog catalog2 : list) {
                delete(catalog2);
            }
            catalogMapper.deleteByPrimaryKey(cata.getId());
        }
        List<Catalog> list = catalogMapper.selectByPid(cata.getPid());
        if(list.size() == 0) {
            cata = catalogMapper.selectByPrimaryKey(cata.getPid());
            cata.setIsParent(false);
            catalogMapper.updateByPrimaryKeySelective(cata);
        }
    }
    
    //按主键查询
    @Override
    public Catalog getCatalogById(long id) {
        // TODO Auto-generated method stub
        return catalogMapper.selectByPrimaryKey(id);
    }
    
    
}
